package cn.kk.day02zuoye.Listener;
/*
 *@author KK on 2022.11.22 19:14
 */

import cn.kk.day02zuoye.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.ArrayList;
import java.util.List;

@WebListener()
public class UserListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
    private List<User> userList;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        userList = new ArrayList<>();
        servletContextEvent.getServletContext().setAttribute("userList",userList);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        User user = (User) httpSessionEvent.getSession().getAttribute("user");
        List<User> userList = (List<User>) httpSessionEvent.getSession().getServletContext().getAttribute("userList");
        userList.remove(user);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        User user = (User) httpSessionBindingEvent.getValue();
        List<User> userList = (List<User>) httpSessionBindingEvent.getSession().getServletContext().getAttribute("userList");
        userList.add(user);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    public UserListener() {

    }
}
